package com.cloudkinto.appletservice.firstvesselorder.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.appletservice.firstvesselorder.AppletFirstVesselOrderService;
import com.cloudkinto.appletservice.firstvesselorder.vo.*;
import com.cloudkinto.common.DicBusinessConstant;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.utils.OrderCodeUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.fbaproduct.FbaProductService;
import com.cloudkinto.service.fbaproduct.vo.FbaProductDetailRes;
import com.cloudkinto.service.file.FileService;
import com.cloudkinto.service.firstvesselorder.vo.FirstVesselOrderAddReq;
import com.cloudkinto.service.firstvesselorder.vo.FirstVesselOrderPackageDetailRes;
import com.cloudkinto.service.firstvesselorder.vo.FirstVesselOrderUpdateReq;
import com.cloudkinto.service.firstvesselorder.vo.FirstVesselUploadCartonabelReq;
import com.cloudkinto.service.storage.StorageService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author zhangyy
 * @since 2020-09-16
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class AppletFirstVesselOrderServiceImpl extends ServiceImpl<FirstVesselOrderDao, FirstVesselOrderDo> implements AppletFirstVesselOrderService {
    @Autowired
    private FirstVesselOrderDao dao;
    @Autowired
    private FirstVesselOrderPackageDao firstVesselOrderPackageDao;
    @Autowired
    private FirstVesselOrderProductDao firstVesselOrderProductDao;
    @Autowired
    private StorageService storageService;
    @Autowired
    private DicBusinessItemDao dicBusinessItemDao;
    @Autowired
    private FbaStorageDao fbaStorageDao;
    @Autowired
    private FileService fileService;
    @Autowired
    private StorageDao storageDao;


    @Override
    public AppletFirstVesselOrderDetailRes detail(Long id) {
        FirstVesselOrderDo entityDo = dao.selectById(id);
        AppletFirstVesselOrderDetailRes res = new AppletFirstVesselOrderDetailRes();
        if (res == null) throw new BizExceptionI18("no.order.info");
        BeanUtils.copyProperties(entityDo, res);
        res.setCustomsClearanceFileUrl(fileService.getFilePath(entityDo.getCustomsClearanceFileId()));
        res.setDeclarationInformationFileUrl(fileService.getFilePath(entityDo.getDeclarationInformationFileId()));
        res.setCommodityFileUrl(fileService.getFilePath(entityDo.getCommodityFileId()));
        res.setDeclarationCertificateFileUrl(fileService.getFilePath(entityDo.getDeclarationCertificateFileId()));

//        DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(entityDo.getStatus());
//        if (businessItemDo != null) {
//            res.setStatus(businessItemDo.getDicItemValue());
//        }
//        res.setResultStatus(getResultStatusStr(entityDo.getResultStatus()));

        StorageDo storageDo = storageDao.selectById(entityDo.getStorageId());
        if (storageDo != null) {
            res.setStorageName(storageDo.getStorageName());
        }

        FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(entityDo.getFbaStorageId());
        if (fbaStorageDo != null) {
            res.setFbaStorageName(fbaStorageDo.getFbaName());
        }

        DicBusinessItemDo logisticsType = dicBusinessItemDao.selectById(entityDo.getLogisticsType());
        if (logisticsType != null) {
            res.setLogisticsTypeName(logisticsType.getDicItemValue());
        }

        res.setIsCloudkintoExportName(entityDo.getIsCloudkintoExport() == 1 ? "是" : "否");
        res.setCustomsTypeName(entityDo.getCustomsType() == 1 ? "报关退税" : "非退税");
        res.setIsPurchaseOfInsuranceName(entityDo.getIsPurchaseOfInsurance() == 1 ? "是" : "否");
//        res.setDistributionTypeName(entityDo.getDistributionType() == 1 ? "上门取件" : "送货到仓");

//        List<FirstVesselOrderPackageDetailRes> packageDetailResList = new ArrayList<>();
//
//        LambdaQueryWrapper<FirstVesselOrderPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        packageDoLambdaQueryWrapper.eq(FirstVesselOrderPackageDo::getOrderId, id);
//        List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos = firstVesselOrderPackageDao.selectList(packageDoLambdaQueryWrapper);
//        if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
//            firstVesselOrderPackageDos.forEach(packageDo -> {
//                FirstVesselOrderPackageDetailRes packageDetailRes = new FirstVesselOrderPackageDetailRes();
//                BeanUtils.copyProperties(packageDo, packageDetailRes);
//                packageDetailRes.setWeight(packageDo.getWeight() * packageDo.getCount());
//
//                List<FbaProductDetailRes> productDetailResList = new ArrayList<>();
//                LambdaQueryWrapper<FirstVesselOrderProductDo> productDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                productDoLambdaQueryWrapper.eq(FirstVesselOrderProductDo::getPackageId, packageDo.getId());
//                List<FirstVesselOrderProductDo> firstVesselOrderProductDos = firstVesselOrderProductDao.selectList(productDoLambdaQueryWrapper);
//                if (!CollectionUtils.isEmpty(firstVesselOrderProductDos)) {
//                    firstVesselOrderProductDos.forEach(productDo -> {
//                        FbaProductDetailRes productDetailRes = fbaProductService.detail(productDo.getProductId());
//                        productDetailRes.setCount(productDo.getCount());
//                        productDetailResList.add(productDetailRes);
//                    });
//                }
//
//                packageDetailRes.setProductList(productDetailResList);
//                packageDetailResList.add(packageDetailRes);
//            });
//        }
//        res.setPackageList(packageDetailResList);
        return res;
    }

    private String getResultStatusStr(Integer resultStatus) {
        if (resultStatus == null)
            return "";
        if (resultStatus == 1) {
            return "当前订单";
        } else if (resultStatus == 2) {
            return "已完成";
        } else if (resultStatus == 3) {
            return "已退回";
        }
        return "";
    }


    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<FirstVesselOrderDo> wrapper = queryBuild(map);
        IPage<FirstVesselOrderDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<AppletFirstVesselOrderPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }


    //查询分页列表之后对列表数据的处理
    private List<AppletFirstVesselOrderPageRes> handlerListAfter(List<FirstVesselOrderDo> list) {
        List<AppletFirstVesselOrderPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(firstVesselOrderDo -> {
                AppletFirstVesselOrderPageRes res = new AppletFirstVesselOrderPageRes();
                res.setId(firstVesselOrderDo.getId());
                res.setOrderNumber(firstVesselOrderDo.getOrderNumber());
                res.setRemark(firstVesselOrderDo.getRemark());
                res.setCreateTime(firstVesselOrderDo.getCreateTime());
//                res.setResultStatus(getResultStatusStr(firstVesselOrderDo.getResultStatus()));
                StorageDo storageDo = storageService.getBaseMapper().selectById(firstVesselOrderDo.getStorageId());
                if (storageDo != null) {
                    res.setStorage(storageDo.getStorageName());
                }
                FbaStorageDo fbaStorageDo = fbaStorageDao.selectById(firstVesselOrderDo.getFbaStorageId());
                if (fbaStorageDo != null) {
                    res.setFbaStorage(fbaStorageDo.getFbaCode() + fbaStorageDo.getFbaName());
                }
                DicBusinessItemDo businessItemDo = dicBusinessItemDao.selectById(firstVesselOrderDo.getStatus());
                if (businessItemDo != null) {
                    res.setStatus(businessItemDo.getDicItemValue());
                }

//                LambdaQueryWrapper<FirstVesselOrderPackageDo> packageDoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                packageDoLambdaQueryWrapper.eq(FirstVesselOrderPackageDo::getOrderId, firstVesselOrderDo.getId());
//                List<FirstVesselOrderPackageDo> firstVesselOrderPackageDos = firstVesselOrderPackageDao.selectList(packageDoLambdaQueryWrapper);
//                int packageCount = 0;
//                double volume = 0;
//                if (!CollectionUtils.isEmpty(firstVesselOrderPackageDos)) {
//                    for (FirstVesselOrderPackageDo packageDo : firstVesselOrderPackageDos) {
//                        packageCount += packageDo.getCount();
//                        volume += packageDo.getLength() * packageDo.getWidth() * packageDo.getHeight() / 1000000;
//                    }
//                }
//                res.setVolume(new BigDecimal(volume).setScale(2, RoundingMode.UP).floatValue());
//                res.setPackageCounts(packageCount);
//
//                if (firstVesselOrderDo.getStatus().equals(DicBusinessItemConstant.seaUnsubmit)) {
//                    res.setIsEdit(1);
//                } else {
//                    res.setIsEdit(2);
//                }

                result.add(res);
            });
        }
        return result;
    }

    private IPage<FirstVesselOrderDo> pageInit(Map<String, String> map) {
        IPage<FirstVesselOrderDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<FirstVesselOrderDo> queryBuild(Map<String, String> map) {
        QueryWrapper<FirstVesselOrderDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("order_number", map.get("keyword"));
        }
        if (StringUtils.isNotBlank(map.get("status"))) {
            wrapper.eq("status", map.get("status"));
        }
        if (StringUtils.isNotBlank(map.get("companyId"))) {
            wrapper.eq("company_id", map.get("companyId"));
        }
        if (StringUtils.isNotBlank(map.get("startDate"))) {
            wrapper.ge("create_time", map.get("startDate"));
        }
        if (StringUtils.isNotBlank(map.get("endDate"))) {
            wrapper.le("create_time", map.get("endDate"));
        }


        return wrapper.orderByDesc("id");
    }


}
